package com.pay.paytoken.activity.lock;

import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;

import com.pay.paytoken.R;
import com.pay.paytoken.activity.PasswordVerificationActivity;
import com.pay.paytoken.base.BaseActivity;

import appUtils.AppUtil;
import appUtils.CustomAlertDoubleBtnDialog;
import appUtils.FingerprintUtil;
import appUtils.LogUtil;
import appUtils.ToastUtil;
import butterknife.Bind;
import weightUtils.digitalLock.DigitalInputView;

import static com.pay.paytoken.activity.lock.LockManager.CANBACK;
import static com.pay.paytoken.activity.lock.LockManager.TYPE;

public class DigitalLockActivity extends BaseActivity implements DigitalInputView.OnDigitalChangeListener {
    private static final int CLEAR_DIGITAL = 0x1;
    private static final int mErrorLimitCount = 5;
    private static final int mFingerErrorLimitCount = 3;
    @Bind(R.id.activity_lock_digital_tv)
    TextView mDigitalTv;
    @Bind(R.id.lock_digital_remark)
    TextView mRemarkTv;
    @Bind(R.id.digital_input_view)
    DigitalInputView mDigitalInputView;
    CancellationSignal mCancel = new CancellationSignal();
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CLEAR_DIGITAL:
                    mDigitalInputView.clearPassDigital();
                    break;
            }
        }
    };
    private long mFirstTime = 0;
    private int mErrorCount = 0;
    private int mFingerErrorCount = 0;
    private boolean mCanBack;
    FingerprintManager.AuthenticationCallback mCallBack;
    //0为数字密码 1为包含指纹解锁 4为修改密码
    private int mType;
    private int mInitType;
    private CustomAlertDoubleBtnDialog mDialog;
    private boolean mIsExceedTime = false;

    @Override
    public int setView() {
        return R.layout.activity_lock_digital;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        mCanBack = intent.getBooleanExtra(CANBACK, true);
        mType = intent.getIntExtra(TYPE, 0);
        mInitType = mType;
        mDialog = new CustomAlertDoubleBtnDialog(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mType = mInitType;
        if (mType == 1) {
            if (mFingerErrorCount < mFingerErrorLimitCount && FingerprintUtil.getFingerprintEnAble(this)) {
                LogUtil.log("FINGER_PRINT_AUTHEN");
                FingerprintUtil.authenticate(DigitalLockActivity.this, null, mCancel, 0, new FingerprintManager.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errorCode, CharSequence errString) {
                        super.onAuthenticationError(errorCode, errString);
                        LogUtil.log("finger is onAuthenticationError errString = " + errString + " errorCode = " + errorCode);
                        if (errorCode == 7) {
                            cancelFingerprint();
                            mIsExceedTime = true;
                        }
                    }

                    @Override
                    public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                        super.onAuthenticationHelp(helpCode, helpString);
                        LogUtil.log("finger is onAuthenticationHelp");
                    }

                    @Override
                    public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                        super.onAuthenticationSucceeded(result);
                        LogUtil.log("finger is onAuthenticationSucceeded");
                        finish();
                    }

                    @Override
                    public void onAuthenticationFailed() {
                        super.onAuthenticationFailed();
                        LogUtil.log("finger is onAuthenticationFailed");
                        passFailure();
                    }
                }, null);
                initFingerDialog();
            } else {
                mType = 0;
            }
            if (!FingerprintUtil.getFingerprintEnAble(this)) {
                ToastUtil.showShort(R.string.current_device_unlock_fingerprint_please_open_system_fingerprint_or_close_app_unlock_fingerprint);
            }
        }
    }

    @Override
    public void initView() {
        mDigitalInputView.setOnDigitalChangeListener(this);
    }

    private void initFingerDialog() {
        if (mIsExceedTime || mType != 1) {
            return;
        }
        mDialog.setTitle(getString(R.string.fingerprint_unlock));
        mDialog.setMsg(getString(R.string.welcome_back_please_touch_fingerprint_key));
        mDialog.hideRightBtn();
        mDialog.setCancelAble(false);
        mDialog.setCancelClickListener(new CustomAlertDoubleBtnDialog.CancelClickListener() {
            @Override
            public void onClick() {
                cancelFingerprint();
            }
        });
        mDialog.showDialog();
    }

    private void cancelFingerprint() {
        if (mCancel != null)
            mCancel.cancel();
        if (mDialog != null)
            mDialog.dismiss();
        mRemarkTv.setText("");
        mType = 0;
        mInitType = 0;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mCanBack) {
                finish();
                return true;
            } else {
                if (System.currentTimeMillis() - mFirstTime > 2000) {
                    ToastUtil.showLong(R.string.again_according_to_exit_program);
                    mFirstTime = System.currentTimeMillis();
                } else {
                    AppUtil.getInstance().exit();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void passFailure() {
        if (mType == 1) {
            mFingerErrorCount++;
            mDialog.setTitle(getString(R.string.one_more_time));
            if (mFingerErrorCount >= mFingerErrorLimitCount) {
                cancelFingerprint();
            }
        } else {
            mErrorCount++;
            mRemarkTv.setText(String.format(getString(R.string.pass_error_you_can_also_enter_again_format), mErrorLimitCount - mErrorCount));
            if (mErrorCount >= mErrorLimitCount) {
                startActivity(new Intent(this, PasswordVerificationActivity.class));
                mErrorCount = 0;
                finish();
            } else {
                mHandler.sendEmptyMessageDelayed(CLEAR_DIGITAL, 200);
            }
        }
    }

    @Override
    public void digitalChange(StringBuilder passCode) {
        mDigitalTv.setText(passCode);
        if (passCode.length() == 6) {
            if (LockManager.getInstance().getDigitalPass().equals(passCode.toString())) {
                finish();
            } else {
                passFailure();
            }
        }
    }
}
